<?php
	
	/** une classe pour modéliser les équipes
	 * @author Sebastian Mosser 
	 */

class Team implements iPersistantData, iHTMLViewable, 
											iLookable, iXMLSerializable {

	private $_id;         ///< Identifiant
	private $_admin;      ///> administrateur balloon de l'equipe 
	private $_name;       ///< Nom de l'équipe
	private $_category;   ///< Catégorie d'équipe d'appartenance
	private $_coach;      ///< Entraineur
	private $_director1;  ///< Dirigeant n°1 
	private $_director2;  ///< Dirigeant n°2
	private $_picture;    ///< Image d'ensemble de l'équipe
	private $_players;    ///< tableaux de joueurs
	private $_matches;	  ///< tableau de matches
	private $_trainings;  ///< tableau des sessions d'entrainements
	private $_schedules;  ///< tableau des horaires d'entrainements
	
	public static $UNKNOWNPIC_SMALL = "unknown-SMALL.png";
	public static $UNKNOWNPIC_LARGE = "unknown-LARGE.png";	
 	private $PIC_PATH;
 	private $PIC_URL;
	public static $SMALL_SUFFIX = "-SMALL";
	public static $LARGE_SUFFIX = "-LARGE";
	
	public static $PLAYER_ROLES = array("1" => "Gardien", 
																			"2" => "Défenseur",
																			"3" => "Milieu Défensif",
																			"4" => "Milieu Offensif",
																			"5" => "Attaquant");
	
	public function __construct($id = -1) {
		$this->_id = $id;
		$this->_players   = array() ; $this->_matches  = array();
		$this->_trainings = array() ; $this->_schedules = array();
		$this->PIC_PATH = BALLOON_FS_PATH . "data/img/teams/";
		$this->PIC_URL  = BALLOON_BASE_URL . "data/img/teams/";
	}
	
	public function xmlExport($e, $t="") {
		$id = $this->_id;
		$name = htmlentities($this->_name,ENT_COMPAT,"UTF-8");
		
		$category = $this->_category;
		$coach = $this->_coach;
		$e->visitMember($coach,"coach");
		
		$d1 = $this->_director1;
		$e->visitMember($d1,"director");
		
		$d2 = $this->_director2;
		$e->visitMember($d2,"director");
		
		$players = "";
		$tmp = $this->_players;
		asort($tmp);
		foreach($tmp as $k => $v) {
			$e->visitMember($k,"player");
			$role = htmlentities(self::$PLAYER_ROLES[$v],ENT_COMPAT,"UTF-8");
			$players .= <<<EOS

			<player>
				<id>${k}</id>
				<role>${role}</role>
			</player>
			
EOS;
		}
		if ($players == "")
			$playersArray = "		<players />";
		else
			$playersArray = "		<players>\n${players}\n		</players>";
			
		$schedules = "";
		foreach($this->_schedules as $k => $v) {
			$day = Date::$days[$v["day"]];
			$field = htmlentities($v["field"],ENT_COMPAT,"UTF-8");
			$begin = htmlentities($v["begin"],ENT_COMPAT,"UTF-8");
			$end = htmlentities($v["end"],ENT_COMPAT,"UTF-8");
			$schedules .= <<<EOS
			<schedule>
				<day>${day}</day>
				<field>${field}</field>
				<begin>${begin}</begin>
				<end>${end}</end>
			</schedule>

EOS;
		}
		if ($schedules == "")
			$scheduleArray = "		<schedules />";
		else
			$scheduleArray = "		<schedules>\n${schedules}\n		</schedules>";
			
		$matches = "";
		foreach($this->_matches as $k => $v){
			$e->visitMatche($k);
			$matches .= "			<matche>${k}</matche>\n";
		}
		if ($matches == "")
			$matcheArray = "		<matches />";
		else
			$matcheArray = "		<matches>\n${matches}		</matches>";
		
		if ($this->_picture == "")
			$img = "none";
		else {
			$ans = $this->computePicFileName($this->_picture);
			$e->insertPicture($ans["large"],$ans["small"]);
			$img = $ans["large"];
		}
		$ans = <<<EOS
	<team id="${id}">
		<picture>${img}</picture>
		<name>${name}</name>
		<category>${category}</category>
		<coach>${coach}</coach>
		<director_1>${d1}</director_1>
		<director_2>${d2}</director_2>
${playersArray}
${scheduleArray}
${matcheArray}
	</team>
EOS;
		$e->insertData("team",$this->_id,$ans);
		
	}
	
	/** Accès en lecture aux membres d'instance **/
	public function getId()        { return $this->_id; }
	public function getName()      { return $this->_name;      }
	public function getAdmin()     { return $this->_admin;     }
	public function getCategory()  { return $this->_category;  }
	public function getCoach()     { return $this->_coach;     }
	public function getDirector1() { return $this->_director1; }
	public function getDirector2() { return $this->_director2; }
	
	public function getPlayers()   { return $this->_players;   }
	public function getSchedules() { return $this->_schedules; }
	public function getMatches()   { return $this->_matches; }
	
	/** Accès en écriture aux variables **/
	public function setAdmin($a)     { $this->_admin = $a;     }
	public function setName($n)      { $this->_name = $n;      }
	public function setCategory($c)  { $this->_category = $c;  }
	public function setCoach($c)     { $this->_coach = $c;     }
	public function setDirector1($d) { $this->_director1 = $d; }
	public function setDirector2($d) { $this->_director2 = $d; }


	private function computePicFileName($ext) {
		$ans = array();
		$ans["small"] = $this->PIC_PATH.$this->_id. self::$SMALL_SUFFIX.$ext;
		$ans["large"] = $this->PIC_PATH.$this->_id. self::$LARGE_SUFFIX.$ext;
		return $ans;
	}
	
	private function computePicUrl($ext) {
		$ans = array();
		$ans["small"] = $this->PIC_URL.$this->_id. self::$SMALL_SUFFIX.$ext;
		$ans["large"] = $this->PIC_URL.$this->_id. self::$LARGE_SUFFIX.$ext;
		return $ans;
	}

	public function setPicture($p='')   { 
		$tmpFile = new Picture($p);
		$ext = $tmpFile->getExtension();
		if (! $ext)
			return False; // Type de fichier non géré par le système
			
		$names = $this->computePicFileName($ext);
		$small = $tmpFile->duplicate($names["small"]);
		$large = $tmpFile->duplicate($names["large"]);
		
		$tmpFile->delete();
		
		$small->resize(133,100);
		$large->resize(1024,768);
		$large->tag(Picture::$TAG_VALUE);
		$this->_picture = $ext;
		return True;
	}
	
	public function delPicture() {
		$ext = $this->_picture;
		$ans = $this->computePicFileName($ext);
		if (file_exists($ans["small"]))
			unlink($ans["small"]);
		if (file_exists($ans["large"]))
			unlink($ans["large"]);
		$this->_picture = "";
	}
	
	/** Récupération des images **/
	public function getSmallPicture() {
		if ($this->_picture == '')
			return $this->PIC_URL . self::$UNKNOWNPIC_SMALL;
		$tmp = $this->computePicUrl($this->_picture);
		return $tmp["small"];
	}
	
	public function getLargePicture() {
		if ($this->_picture == '')
			return $this->PIC_URL . self::$UNKNOWNPIC_LARGE;
		$tmp = $this->computePicUrl($this->_picture);
		return $tmp["large"];
	}
	
	/** Ajout et suppression dans les tableaux **/
	public function addPlayer($playerId,$role) {
		$this->_players[$playerId] = $role;
	}
	
	public function delPlayer($playerId) {
		if (array_key_exists($playerId,$this->_players))
			unset($this->_players[$playerId]);
	}
	
	public function addMatche($matcheId) {
		$this->_matches[$matcheId] = True;
	}
	
	public function delMatche($matcheId) {
		if (array_key_exists($matcheId,$this->_matches))
			unset($this->_matches[$matcheId]);
	}
	
	public function addTraining($trainingId) {
		$this->_trainings[$trainingId] = True;
	}
	
	public function delTraining($trainingId) {
		if (array_key_exists($trainingId,$this->_trainings))
			unset($this->_trainings[$trainingId]);
	}
	
	public function addSchedule($d,$f,$b,$e,$scheduleId = -1) {
		$content = array();
		$content["day"]   = $d; $content["field"] = $f;
		$content["begin"] = $b; $content["end"]   = $e;
		
		if ($scheduleId == -1) {
			$this->_schedules[-1] = $content;
			//$this->manageScheduleLnk();
		}
		else
			$this->_schedules[$scheduleId] = $content;
	}
	
	public function delSchedule($scheduleId) {
		if (array_key_exists($scheduleId, $this->_schedules))
			unset($this->_schedules[$scheduleId]);
	}
	
	/** Implémentation de la CRUD **/
	
	public static function createTable() {
		
		/** Recuperation de la base de données **/
		$myDb = Database::getSingleton();
		
		/** Table principale **/
		$sql  = "CREATE TABLE IF NOT EXISTS `team` (\n";
		$sql .= "  `id`  INTEGER NOT NULL PRIMARY KEY auto_increment, \n";
		$sql .= "  `admin`      INTEGER      NOT NULL, \n";
		$sql .= "  `name`       VARCHAR(50)  NOT NULL, \n";
		$sql .= "  `category`   INTEGER      NOT NULL, \n";
		$sql .= "  `coach`      INTEGER      NOT NULL, \n ";
		$sql .= "  `director_1` INTEGER      NOT NULL, \n";
		$sql .= "  `director_2` INTEGER      NOT NULL, \n";
		$sql .= "  `picture`    VARCHAR(255) NOT NULL);";
		$myDb->execute($sql);
		
		/** Liaisons avec les joueurs **/
		$sql  = "CREATE TABLE IF NOT EXISTS `team_member_lnk` (\n";
		$sql .= "  `id`  INTEGER NOT NULL PRIMARY KEY auto_increment, \n";
		$sql .= "  `team_id`   INTEGER NOT NULL, \n ";
		$sql .= "  `member_id` INTEGER NOT NULL, \n ";
		$sql .= "  `role_id`   INTEGER NOT NULL);   ";
		$myDb->execute($sql);
		
		/** Liaisons avec les matches **/
		$sql  = "CREATE TABLE IF NOT EXISTS `team_matche_lnk` (\n";
		$sql .= "  `id`  INTEGER NOT NULL PRIMARY KEY auto_increment, \n";
		$sql .= "  `team_id`   INTEGER NOT NULL, \n";
		$sql .= "  `matche_id` INTEGER NOT NULL); ";
		$myDb->execute($sql);
		
		/** Liaisons avec les sessions d'entrainements **/
		$sql  = "CREATE TABLE IF NOT EXISTS `team_training_lnk` (\n";
		$sql .= "  `id`  INTEGER NOT NULL PRIMARY KEY auto_increment, \n";
		$sql .= "  `team_id`     INTEGER NOT NULL, \n";
		$sql .= "  `training_id` INTEGER NOT NULL); ";
		$myDb->execute($sql);

		/** Liaisons avec les horaires d'entrainements **/
		$sql  = "CREATE TABLE IF NOT EXISTS `team_schedule_lnk` (\n";
		$sql .= "  `id`  INTEGER NOT NULL PRIMARY KEY auto_increment, \n";
		$sql .= "  `team_id`     INTEGER     NOT NULL, \n";
		$sql .= "  `day`         INTEGER     NOT NULL, \n";
		$sql .= "  `field`       VARCHAR(50) NOT NULL, \n";
		$sql .= "  `begin`       VARCHAR(5)  NOT NULL, \n";
		$sql .= "  `end`         VARCHAR(5)  NOT NULL); ";
		$myDb->execute($sql);
		
		/** Table de présence aux entrainements **/
		$sql  = "CREATE TABLE IF NOT EXISTS `team_presence` (\n";
		$sql .= "  `id` INTEGER NOT NULL PRIMARY KEY auto_increment, \n";
		$sql .= "  `team_id` 	INTEGER 	NOT NULL, \n";
		$sql .= "  `date` 		VARCHAR(10) NOT NULL, \n";
		$sql .= "  `presence` 	LONGTEXT 	NOT NULL); ";
		$myDb->execute($sql);

	}
	
	public static function dropTable() {
		$myDb = Database::getSingleton();
		$myDb->execute("DROP TABLE IF EXISTS `team`;");
		$myDb->execute("DROP TABLE IF EXISTS `team_member_lnk`  ;");
		$myDb->execute("DROP TABLE IF EXISTS `team_matche_lnk`  ;");
		$myDb->execute("DROP TABLE IF EXISTS `team_training_lnk`;");
		$myDb->execute("DROP TABLE IF EXISTS `team_schedule_lnk`;");
		$myDb->execute("DROP TABLE IF EXISTS `team_presence`;");
	}
	
	/** Gestion des laissons **/
	private function manageLnk() {
		$this->managePlayerLnk();
		$this->manageScheduleLnk();
		$this->manageMatchesLnk();
	
	}
	
	private function manageMatchesLnk() {
	
		// Récupération de la base de données
	  $myDb = Database::getSingleton();
	  $id = $this->_id;
	  
	  
	  // Récupération des infos présentes sur les fonctions :
	  $sql = "SELECT * FROM `team_matche_lnk` WHERE `team_id` = $id";
	  $ans = $myDb->execute($sql);
	  
	  $tmp = $this->_matches;
	  
	  while (($row = Database::assoc($ans)) != False) {
	    if (array_key_exists($row["matche_id"],$tmp)) {
	      unset($tmp[$row["matche_id"]]);
	    }
	    else {
	    	// On n'est plus dans les matches de l'équipe
	    	$query = 
	    		 "DELETE FROM `team_matche_lnk` WHERE `id` = " . $row["id"];
	    	// On se supprime des données persistantes
	    	$myDb->execute($query);
	    }
	  } // fin du while
	  // A ce stade, le tableau temporaire contient uniquement les tuple a ajouter
	  $id = Database::escape($this->_id);
	  foreach($tmp as $k => $v) {
	  	$matche = Database::escape($k);
	  	$sql  = "INSERT INTO `team_matche_lnk` VALUES ('', ";
	  	$sql .= "  '$id', '$matche');";
	  	$myDb->execute($sql);
	  }
	  // synchronisation finie !
	}
	
	private function managePlayerLnk() {
		// Récupération de la base de données
	  $myDb = Database::getSingleton();
	  $id = $this->_id;
	  
	  
	  // Récupération des infos présentes sur les fonctions :
	  $sql = "SELECT * FROM `team_member_lnk` WHERE `team_id` = $id";
	  $ans = $myDb->execute($sql);
	  
	  $tmpPlayers = $this->_players;
	  
	  while (($row = Database::assoc($ans)) != False) {
	    if (array_key_exists($row["member_id"],$tmpPlayers)) {
	      // quelque chose dans la base ...
	      $volatileRole   = $tmpPlayers[$row["member_id"]];
	      $persistantRole = $row["role_id"];
	      
	      if ( $volatileRole != $persistantRole ) {
	      	// Les données ont changée ... database update
	      	$r = Database::escape($volatileRole);
	      	$query  = "UPDATE `team_member_lnk` SET \n";
	      	$query .= "  `role_id` = $r ";
	      	$query .= "  WHERE `id` = " . $row["id"];
	      	$myDb->execute($query);
	      } 
	     
	      // Quoi qu'il arrive, on dégage du tableau temporaire
	      unset($tmpPlayers[$row["member_id"]]);
	    }
	    else {
	    	// On n'est plus dans les membres de l'équipe
	    	$query = 
	    		 "DELETE FROM `team_member_lnk` WHERE `id` = " . $row["id"];
	    	// On se supprime des données persistantes
	    	$myDb->execute($query);
	    }
	  } // fin du while sur team_member_lnk
	  // A ce stade, le tableau temporaire contient uniquement les tuple a ajouter
	  $id = Database::escape($this->_id);
	  foreach($tmpPlayers as $k => $v) {
	  	$member = Database::escape($k);
	  	$role   = Database::escape($tmpPlayers[$k]);
	  	$sql  = "INSERT INTO `team_member_lnk` VALUES ('', ";
	  	$sql .= "  '$id', '$member', '$role');";
	  	$myDb->execute($sql);
	  }
	  // synchronisation finie !
	} // fin de managePlayerLnk()
	
	
	private function manageScheduleLnk() {
		// Récupération de la base de données
	  $myDb = Database::getSingleton();
	  $id = $this->_id;
	  
	  
	  // Récupération des infos présentes sur les fonctions :
	  $sql = "SELECT * FROM `team_schedule_lnk` WHERE `team_id` = $id";
	  $ans = $myDb->execute($sql);
	  
	  $tmpSchedules = $this->_schedules;
	  
	  while (($row = Database::assoc($ans)) != False) {
	    if (array_key_exists($row["id"],$tmpSchedules)) {
	      // quelque chose dans la base ...
	      $volatileSchedule   = $tmpSchedules[$row["id"]];
	      $persistantSchedule = array();
	      $persistantSchedule["day"]   = $row["day"];
	      $persistantSchedule["field"] = $row["field"];
	      $persistantSchedule["begin"] = $row["begin"];
	      $persistantSchedule["end"]   = $row["end"];
	      
	      if ( $volatileSchedule != $persistantSchedule ) {
	      	// Les données ont changée ... database update
	      	$d = Database::escape($volatileSchedule["day"]);
					$f = Database::escape($volatileSchedule["field"]);
					$b = Database::escape($volatileSchedule["begin"]);
					$e = Database::escape($volatileSchedule["end"]);
	      	
	      	$query  = "UPDATE `team_schedule_lnk` SET \n";
	      	$query .= "  `day`   = '$d', \n ";
	      	$query .= "  `field` = '$f', \n";
	      	$query .= "  `begin` = '$b', \n";
					$query .= "  `end`   = '$e' \n";
	      	$query .= "  WHERE `id` = " . $row["id"];
	      	$myDb->execute($query);
	      } 
	     
	      // Quoi qu'il arrive, on dégage du tableau temporaire
	      unset($tmpSchedules[$row["id"]]);
	    }
	    else {
	    	// On n'est plus dans les horaires de l'équipe
	    	$query = 
	    		 "DELETE FROM `team_schedule_lnk` WHERE `id` = " . $row["id"];
	    	// On se supprime des données persistantes
	    	$myDb->execute($query);
	    }
	  } // fin du while sur team_member_lnk
	  
	  // A ce stade, le tableau temporaire contient uniquement les tuple a ajouter
	  $id = Database::escape($this->_id);
	  foreach($tmpSchedules as $k => $v) {
	  	$d = Database::escape($v["day"]);
			$f = Database::escape($v["field"]);
			$b = Database::escape($v["begin"]);
			$e = Database::escape($v["end"]);
	  	$sql  = "INSERT INTO `team_schedule_lnk` VALUES ('', ";
	  	$sql .= "  '$id', '$d', '$f', '$b', '$e');";
	  	$myDb->execute($sql);
	  }
	  // synchronisation finie !
	} // fin de manageScheduleLnk()
	
	public function create() {
		if ($this->_id != -1)
			throw new Exception('Still existing',1);

		$admin     = Database::escape($this->_admin);
		$name      = Database::escape($this->_name);
		$category  = Database::escape($this->_category);
		$coach     = Database::escape($this->_coach);
		$director1 = Database::escape($this->_director1);
		$director2 = Database::escape($this->_director2);
		$picture   = Database::escape($this->_picture);

		$query = <<<EOS
INSERT INTO `team` VALUES 
  ( '', '$admin', '$name', '$category', '$coach', '$director1',
    '$director2','$picture' );
EOS;
		$myDb = Database::getSingleton();
		$ans = $myDb->executeInsert($query);
		$this->_id = $ans[0];
		// Gestion des liasons
		$this->manageLnk();
	}
	
	public static function read($id) {
		$id = Database::escape($id);
		
		// chargement de la table principale
		$sql = "SELECT * FROM `team` WHERE `id` = $id";
		$myDb = Database::getSingleton();
		$ans = Database::assoc($myDb->execute($sql));
		
		if (! $ans)
			throw new Exception("Unknown team id !",1);
		
		$aTeam = new Team($id);
		$aTeam->setAdmin($ans["admin"]);
		$aTeam->setName($ans["name"]);
		$aTeam->setCategory($ans["category"]);
		$aTeam->setCoach($ans["coach"]);
		$aTeam->setDirector1($ans["director_1"]);
		$aTeam->setDirector2($ans["director_2"]);
		$aTeam->_picture = $ans["picture"];
		
		// Chargement des joueurs :
		$sql = "SELECT * FROM `team_member_lnk` WHERE `team_id` = $id";
		$ans = $myDb->execute($sql);
		while (($row = Database::assoc($ans)) != False)
			$aTeam->addPlayer($row["member_id"],$row["role_id"]);
		
		// Chargement des matches :
		$sql = "SELECT * FROM `team_matche_lnk` WHERE `team_id` = $id";
		$ans = $myDb->execute($sql);
		while (($row = Database::assoc($ans)) != False)
			$aTeam->addMatche($row["matche_id"]);
		
		// Chargement des sessions d'entrainements :
		$sql = "SELECT * FROM `team_training_lnk` WHERE `team_id` = $id";
		$ans = $myDb->execute($sql);
		while (($row = Database::assoc($ans)) != False)
			$aTeam->addTraining($row["training_id"]);
		
		// Chargement des horaires d'entrainements :
		$sql = "SELECT * FROM `team_schedule_lnk` WHERE `team_id` = $id";
		$ans = $myDb->execute($sql);
		while (($row = Database::assoc($ans)) != False) {
			$aTeam->addSchedule($row["day"],$row["field"],$row["begin"],$row["end"],
													$row["id"]);
		}

		// On renvoi le bébé
		return $aTeam;
	}
	
	public function update() {
		$myDb = Database::getSingleton();
		
		$id        = Database::escape($this->_id); 
		$admin     = Database::escape($this->_admin);
		$name      = Database::escape($this->_name);
		$category  = Database::escape($this->_category);
		$coach     = Database::escape($this->_coach);
		$director1 = Database::escape($this->_director1);
		$director2 = Database::escape($this->_director2);
		$picture   = Database::escape($this->_picture);
		
		$sql = <<<EOS
UPDATE `team` SET 
	`admin`      = '$admin',   
	`name`       = '$name',     
	`category`   = '$category', 
	`coach`      = '$coach',     
	`director_1` = '$director1',
	`director_2` = '$director2', 
	`picture`    = '$picture'
WHERE `id` = $id;
EOS;

		$myDb->execute($sql);
		$this->manageLnk();
	}
	
	public function delete() {
	
		$id = Database::escape($this->_id);
		$myDb = Database::getSingleton();
		
		// On vire le tuple principal
		$sql = "DELETE FROM `team` WHERE `id` = $id;";
		$myDb->execute($sql);
		
		// On dégage les liaisons vers les joueurs :
		$sql = "DELETE FROM `team_member_lnk` WHERE `team_id` = $id";
		$myDb->execute($sql);
		
		// On dégage les horaires d'entrainenemnts
		$sql = "DELETE FROM `team_schedule_lnk` WHERE `team_id` = $id";
		$myDb->execute($sql);
		
		// On dégage des matches
		$sql = "DELETE FROM `team_matche_lnk` WHERE `team_id` = $id";
		$myDb->execute($sql);
		foreach($this->_matches as $k => $v) {
			$aMatche = Matche::read($k);
			$aMatche->delete();
		}
		
		// On dégage les présences aux entrainenemnts
		$sql = "DELETE FROM `team_presence` WHERE `team_id` = $id";
		$myDb->execute($sql);
	
	}
	
	public function tag() {
		$tmp = array();
		$tmp[0] = "Team";
		$tmp[1] = $this->_id;
		return $tmp;
	}
	
	public function soundsLike($o) {
		return ($this->_coach == $o->_coach); 
	}
	
	/** Fin de la persistance des données **/
	
	/** Interface de Vision HTML **/
	
	public function displayLong() {

		$cat   = TeamCategory::read($this->_category);
		$title = "[ " .$cat->displayLong() . " ] " . $this->_name;
		
		$admin = User::read($this->_admin);
		$admin = $admin->displayShort();
		
		try {
			$coach = Member::read($this->_coach);
			$coach = $coach->displayName();
		} 
		catch(Exception $e) {
			$coach = '<span class="error"> Inconnu </span>';
		}
		
		try {
			$d1    = Member::read($this->_director1);
			$d1    = $d1->displayName();
		} 
		catch(Exception $e) {
			$d1 = '<span class="error"> Inconnu </span>';
		}
		
		try {
			$d2    = Member::read($this->_director2);
			$d2    = $d2->displayName();
		} 
		catch(Exception $e) {
			$d2 = '<span class="error"> Inconnu </span>';
		}
		
		
		
		$page = <<<EOS
<div align="center">
	<table class="resultset">
		<tr> 
			<th colspan="4" align="center"> ${title} </th> 
		</tr>
		<tr> 
			<td><strong> Entraineur </strong> </td> 
			<td> ${coach} </td>
			<td><strong> Administrateur </strong> </td> 
			<td> <code> ${admin} </code> </td>
		</tr>
		<tr>
			<td> <strong> Dirigeant </strong> </td> 
			<td> ${d1} </td>
			<td> <strong> Dirigeant </strong> </td> 
			<td> ${d2} </td>
		</tr>
	</table>
</div>
EOS;
		return $page;
	}
	
	public function displayShort() {
		$cat   = TeamCategory::read($this->_category);
		$title = "[".$cat->displayShort() . "] " . $this->_name;
		return $title;
	
	}
	
	public function displayInline($scriptUrl="") {
		$admin = User::read($this->_admin);
		$admin = $admin->displayShort();
		
		$coach = "";
		try {
			$coach = Member::read($this->_coach);
			$coach = $coach->displayName();
		} 
		catch(Exception $e) {
			$coach = '<span class="error"> Inconnu </span>';
			$coach = $coach->displayName();
		}
		
		$d1 = "";
		try {
			$d1    = Member::read($this->_director1);
			$d1    = $d1->displayName();
		} 
		catch(Exception $e) {
			$d1 = '<span class="error"> -- </span>';
		}
		
		$d2 = "";
		try {
			$d2    = Member::read($this->_director2);
			$d2    = $d2->displayName();
		} 
		catch(Exception $e) {
			$d2 = '<span class="error"> -- </span>';
		}
		
		$result = "";
		if ($scriptUrl == "") {
			$result .= "<td> " . $this->displayShort() . "</td>";
		}
		else {
			$result .= "<td> <a href=\"$scriptUrl?id=".$this->_id."\">";
			$result .= $this->displayShort() . "</a> </td>";
		}
		$result .= "<td> " . $coach ."</td>";
		$result .= "<td>" . $d1 . "</td>";
		$result .= "<td>" . $d2 . "</td>";
		$result .= "<td> <code>" . $admin . "</code></td>";
		return $result;
	
	}
	
	/** Fin de la vision HTML **/
	
	/** Interface de recherche **/
	
	// Le filtre est la saison ...
	public static function lookFor($filter) {
		$cat = TeamCategory::lookFor($filter);
		
		$i = 0;
		$query = "SELECT * FROM `team` WHERE ";
		while (($row = Database::assoc($cat)) != False) {
			$id = $row["id"];
			$query .= "`category` = " . $id . " OR ";
			$i++;
		}
				
		if ($i == 0)
			return False;
		// On vire le ' OR ' en trop a la fin
		$query = substr($query,0,strlen($query)-4);
		//var_dump($query) ;
		$myDb = Database::getSingleton();
		return $myDb->execute($query);
	}
	
	public static function showResult($resultSet, $scriptUrl="") {
		$i = 0;	
		// Remplissage du tableau de résultats :
		$result = array();
		if ($resultSet) {
			while (($row = Database::assoc($resultSet)) != False) {
				$aTeam = Team::read($row["id"]);
				$result[$aTeam->displayShort()] = 
											"<tr> " . $aTeam->displayInline($scriptUrl) . "</tr> \n";
				$i++;
			}
		}
		if ($i == 0) {
			$ans = "<div align=\"center\"><span class=\"error\"> ";
			$ans .= "Aucune équipe pour la saison sélectionnée ! ";
			$ans .= "</span> </div>";
			return $ans;
		}
		

		
		$content = "";
		
		ksort($result);
		foreach ( $result as $v)
			$content .= $v;
		
		return self::getTableHeader() . $content . self::getTableFooter();
		
	}
	
	// On renvoie un tableau d'équipes accessible en écriture pour $userId
	public static function getManagableTeams($season, $userId) {
	
		$theAll = self::lookFor($season);
		
		$result = array();
		while (($row = Database::assoc($theAll)) != False) {
			$aTeam = Team::read($row["id"]);
			// On ajoute si on est admin d'équipe ou admin de la catégorie
			if ($aTeam->canEdit($userId))
				$result[$aTeam->displayShort()] = $row["id"];
		}
		ksort($result);
		return $result;
	}
	
	public static function getTableHeader() {
		$header = "<div align=\"center\"><table class=\"resultset\">";
		$header .= "<tr> <th> Nom </th> <th> Entraineur </th> <th colspan=\"2\">Dirigeants</th> <th> Administrateur Balloon</th> </tr>";
		return $header;
	}
	
	public static function getTableFooter() {
		return "</table> </div>";
	}
	
	/** Fin de l'interface de recherche **/

	public function canEdit($userId) {
		$aCat = TeamCategory::read($this->getCategory());
		return ($this->getAdmin() == $userId or $aCat->getUser() == $userId);
	}
	
	public static function getRolesAsList($selected = -1) {
		$result = "";
		asort(self::$PLAYER_ROLES);
		foreach(self::$PLAYER_ROLES as $k => $v) {
			if ($k == $selected)
				$result .= "<option value=\"$k\" selected > $v </option>\n";
			else
				$result .= "<option value=\"$k\" > $v </option>\n";
		}
		return $result;
	}
	
	public static function getTeamsAsList($selected = -1) {
		$teams = self::lookFor(Login::seasonChoosen(False));
		
		$tmp = array();
		while (($row = Database::assoc($teams)) != False) {
			$aTeam = Team::read($row["id"]);
			$tmp[$aTeam->displayShort()] = $row["id"];
		}
		ksort($tmp);
		
		$ans = "";
		foreach ($tmp as $k => $v) {
			$s = "";
			if ($v == $selected)
				$s = "selected";
			$ans .= "<option value=\"$v\" $s>  $k </option>";
		}
		return $ans;
	}
	
	public function displaySheet() {
		$overview = $this->displayLong();
		
		$players = "";
		$tmpArray = array();
		$p = $this->_players;
		foreach($p as $k => $v) {
			$aMember = Member::read($k);
			$value = $aMember->prepare();
			$licence = $value["licenceNo"];
			$name = $value["name"];
			$birthDate = $value["birthDate"];
			$role = self::$PLAYER_ROLES[$v["role"]];
			$phone = $value["phone"];
			$cellPhone = $value["cellPhone"];
			$table = <<<EOS
<tr> 
	<td> $licence </td> <td> $name </td> <td> $birthDate </td>
	<td> $role </td> <td> $phone </td> <td> $cellPhone </td>
</tr>
EOS;
			$tmpArray[$name] = $table;
		}
		ksort($tmpArray);
		
		foreach($tmpArray as $k => $v)
			$players .= $v;
			
		if ($players == "") {
			$players  = "<div align=\"center\"><span class=\"error\">";
			$players .= "Aucun joueur inscrit dans cette équipe ... ";
			$players .= "</span> </div>";
		}	
		else {
			$tmp = <<<EOS
<div align="center">
<table class="resultset">
<tr>
	<th> Licence </th> <th> Nom </th> <th> Date de Naissance </th>
	<th> Poste </th> <th> Tel. Fixe </th> <th> Tel. Portable </th>
</tr>
$players
</table>
</div>

EOS;
			$players = $tmp;
		}
		$page = <<<EOS
$overview

<h2> Joueurs Permanents </h2>
$players

EOS;
		return $page;
	}
	
}
?>